﻿using Reborn.Contracts.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Reborn.Plugins
{
    public class PluginsServiceProvider
    {

        /// <summary>
        /// 插件容器
        /// </summary>
        Dictionary<string, PluginItem> _plugins = new Dictionary<string, PluginItem>();


        /// <summary>
        /// 构造函数
        /// </summary>
        public PluginsServiceProvider() { 
        }

        private static PluginsServiceProvider _instance = null;
        public static PluginsServiceProvider Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new PluginsServiceProvider();
                }
                return _instance;
            }
        }

        /// <summary>
        /// 获取插件列表
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, PluginItem> GetPlugins()
        { 
            return _plugins;
        }

        /// <summary>
        /// 获取所有插件程序集
        /// </summary>
        /// <returns></returns>
        public List<Assembly> GetPluginsAssembly()
        {
            List<Assembly> assemblies = new List<Assembly>();

            foreach (var item in _plugins)
            {
                    assemblies.Add(item.Value.Assembly);
            }
            return assemblies;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="pluginsDllPaths"></param>
        public void Register(string[] pluginsDllPaths)
        {
            foreach (var item in pluginsDllPaths)
            {
                LoadAssembly(item);
            }
        }

        /// <summary>
        /// 根据目录加载插件
        /// </summary>
        /// <param name="pluginsDllPath"></param>
        void LoadAssembly(string pluginsDllPath)
        {
            if (!Directory.Exists(pluginsDllPath)) return;
            string[] filepath = Directory.GetFiles(pluginsDllPath, "*.dll");
            foreach (string file in filepath)
            {
                Load(file);
            }
        }

        /// <summary>
        /// 加载应用程序域
        /// </summary>
        /// <param name="dllPath"></param>
        /// <param name="pluginName"></param>
        /// <returns></returns>
        public bool Load(string dllPath,string pluginName = "")
        {
            if(string.IsNullOrEmpty(pluginName)) pluginName = Path.GetFileNameWithoutExtension(dllPath);

            if (_plugins.ContainsKey(pluginName)) return false;

            //根据路径加载文件下的程序集
            Assembly ass = Assembly.LoadFrom(dllPath);

            //获取程序集中所有公有的类
            Type[] tclass = ass.GetExportedTypes();
            //获取接口的类
            Type tform = typeof(IPlugin);

            //遍历插件的所有公共类
            foreach (Type t in tclass)
            {
                try
                {
                    //判断接口是否能与插件的类对接
                    if (tform.IsAssignableFrom(t))
                    {
                        IPlugin plugin = Activator.CreateInstance(t) as IPlugin;

                        var loader = new AssemblyDynamicLoader(pluginName);
                        loader.LoadAssembly(dllPath);


                        PluginItem pluginItem = new PluginItem();
                        pluginItem.AssemblyDynamicLoader = loader;
                        pluginItem.Plugin = plugin;
                        pluginItem.Assembly = ass;

                        plugin.Init();

                        _plugins.Add(pluginName, pluginItem);


                        return true;
                    }
                }
                catch 
                {

                }
            }

            return false;
        }

        /// <summary>
        /// 卸载应用程序域
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public bool Unload(string name)
        {
            if (!_plugins.ContainsKey(name)) return false;
            var pluginItem = _plugins[name];
            pluginItem.AssemblyDynamicLoader.Unload();

            _plugins.Remove(name);

            return true;
        }
    }
}
